<!--
 * @Author: ckk
 * @Date: 2022-08-11 13:20:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-11-08 17:17:37
 * @Description: 首页定制化
-->
<template>
  <div
    class="home"
    :style="{'background-color': homeTemplateJson.bgColor, backgroundImage: 'url(' + homeTemplateJson.bgImg + ')',}">
    <div class="header" :style="{background:headColor}">
      <component :is="components[headList.component]" :datas="headList" :color="headColor" v-if="headList"/>
      <component :is="components[navList.component]" :datas="navList" @changeData="navChange" :navActive="checkActive"/>
    </div>
    <div class="container">
      <component :is="components[item.component]" :datas="item"  v-for="(item,index) in channelList" :key="index" :ref="item.component"/>
      <iframe title="" :src="iframeUrl" frameborder="0" v-if="iframeUrl"></iframe>
    </div>
    <component :is="components.tabBar" :datas="tabBar" :active="active" v-if="Object.keys(tabBar).length>0" @update="changeActive"/>
  </div>
</template>
<script>
import { components, components1, matchingData } from '../../common/setting';
import { getVersion, getMain, getPart } from '../../api/getContentApi';
import { getParameter, getLink, getParam } from '../../common/comfun';
import { authenticationServices, baseServices } from '@/api';
export default {
  components: components,
  data () {
    return {
      iframeUrl: '', // 链接H5
      components: components1,
      tabBar: {}, // 底部导航接口数据
      mainList: [], // 装修页面路径列表
      homeList: [], // 首页信息接口数据
      headList: {}, // 头部固定位接口数据
      navList: {}, //  选项卡接口数据
      headColor: '',
      currentSubjectCode: '', // 当前选中的学科
      channelList: [], // 频道页接口数据
      active: 0,
      checkActive: 0,
      templateType: '', // 产品类型
      authenticationInfo: {}, // 鉴权信息
      homeTemplateJson: {},
      ids: ''
    };
  },
  async created () {
    console.log(window.location.href, '路径');
    // 智桂通扫码页面重新加载底部也要重置为0
    // const activeNum = localStorage.getItem('active');
    // this.active = activeNum ? Number(activeNum) : 0;
    await this.authentication();
    await this.getTemVips();
  },
  methods: {
    /**
     * @author: ckk
     * @description: 鉴权接口
     * @return {*}
     */
     async authentication () {
      const res = await authenticationServices.getAuthentication();
      if (res.code === '200') {
        this.authenticationInfo = res.data;
        const gradeCode = localStorage.getItem('gradeCode'),
          useVips = this.authenticationInfo.stageMemberLevels.filter(item => item.stageCode === gradeCode),
          courseIds = this.authenticationInfo.courseIds;
        if (useVips[0]) {
          localStorage.setItem('useVips', JSON.stringify(useVips[0].memberLevels));
        }
        localStorage.setItem('courseIds', courseIds);
        localStorage.setItem('permitSell', res.data.permitSell);
        this.templateType = this.decideType(res.data.permitSell);
        localStorage.setItem('templateType', this.templateType);
        const versionJson = await getVersion(),
        fiterOne = versionJson.filter(item => item.domainName === this.templateType),
        mainType = fiterOne.length === 0 ? versionJson[0].domainName : fiterOne[0].domainName,
        mainId = fiterOne.length === 0 ? versionJson[0].templateDataId : fiterOne[0].templateDataId,
        mainJson = await getMain({ mainType, mainId });
        this.mainList = mainJson;
        localStorage.setItem('mainList', JSON.stringify(mainJson));
        await this.getTabbar();
      }
    },
    /**
     * @author: ckk
     * @description: 轮播图渲染
     * @return {*}
     */
    getColor (color) {
      this.headColor = color;
    },
    /**
     * @author: ckk
     * @description: 过滤属于哪个模板
     * @param {*} permitSell
     * @return {*}
     */
    decideType (permitSell) {
      // 如果是组网，使用组网收费
      if (window.location.host.indexOf('zw') > -1) {
        return 'zw';
      } else if (permitSell === 0 || permitSell === 1 || permitSell === 5) {
        return 'vip';
      } else if (permitSell === 2) {
        if (this.isFreeAreaVIP()) {
          return 'vip';
        } else {
          return 'free';
        }
      } else {
        return 'zw';
      }
    },
    /**
     * @author: ckk
     * @description: 判断免费区域的付费模板
     * @return {*}
     */
    isFreeAreaVIP () {
      const gradeCode = localStorage.getItem('gradeCode'),
        useVips = this.authenticationInfo.stageMemberLevels.filter(item => item.stageCode === gradeCode),
        courseIds = this.authenticationInfo.courseIds;
      if (courseIds.length > 0) {
        return true;
      } else if (useVips.length > 0) {
        const memberLevel = useVips[0].memberLevels.filter(item => item === 3 || item === 4);
        if (memberLevel.length > 0) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    },
    // 获取VIP数据
    async getTemVips () {
      let vipsArr = [];
      const params = { ids: this.ids }, res = await baseServices.getTemVips(params);
      if (res.code === '200') {
        vipsArr = res.data;
        localStorage.setItem('vipsArr', JSON.stringify(vipsArr));
      }
    },
    /**
     * @description: 点击学科入口
     * @param {*} url
     * @Author: ckk
     * @Date: 2022-09-01 14:40:10
     * @return {*}
     */
    async subjectEnter (url) {
      const activeIndex = this.navList.setStyle.optionList.findIndex(item => item.url === url);
      if (activeIndex !== -1) {
      const item1 = this.navList.setStyle.optionList.filter(item => item.url === url)[0],
      query = {
        url: item1.url,
        color: item1.bgcolor,
        navActive: activeIndex,
        info: item1.name
      };
      await this.navChange(query);
      }
    },
    /**
     * @description: 点击频道导航
     * @param {*} name
     * @Author: ckk
     * @Date: 2022-08-23 17:11:27
     * @return {*}
     */
    async navChange (item) {
      this.channelList = [];
      this.iframeUrl = '';
      localStorage.setItem('currentSubjectCode', '');
      if (item) {
        this.checkActive = item.navActive;
        this.headColor = item.color;
        const urlname = getParameter(item.url, 'alias'),
        homeRes = await getPart(this.filterPath('alias', urlname), this.templateType);
        this.homeTemplateJson = JSON.parse(homeRes.templateJson);
        if (item.url.indexOf('.json') !== -1) {
          const url = getParameter(item.url, 'alias'),
          channelRes1 = await getPart(this.filterPath('alias', url), this.templateType);
          if (channelRes1) {
            this.channelList = JSON.parse(channelRes1.component);
            this.currentSubjectCode = JSON.parse(channelRes1.templateJson).subjectCode;
            localStorage.setItem('currentSubjectCode', this.currentSubjectCode);
            let newArrids = [];
            this.channelList.forEach(item => {
              if (item.setStyle.imageList !== undefined) {
                item.setStyle.imageList.map(ite => {
                  newArrids.push(ite.id);
                });
              }
            });
            newArrids = newArrids.filter(item => item !== undefined);
            this.ids = newArrids.toString();
            // this.getTemVips();
          }
        } else {
          this.iframeUrl = JSON.parse(item.url).mobileUrl ? (window.location.origin + JSON.parse(item.url).mobileUrl) : '';
        }
      }
    },
    /**
     * @description: 改变底部导航的值
     * @param {*} value
     * @Author: ckk
     * @Date: 2022-08-22 19:51:07
     * @return {*}
     */
    async changeActive (value) {
      if (value.index !== this.active) {
        this.active = value.index;
        localStorage.setItem('active', this.active);
        if (value.urlname.indexOf('.json') !== -1) {
          await this.getHome(value.urlname);
        } else if (getLink(value.urlname)) {
          const linkList = getLink(value.urlname).split('&'),
          params = getParam(getLink(value.urlname), 'cuparam');
          this.$router.push({ path: linkList[0], query: params ? JSON.parse(params) : '' });
        } else {
          this.$toast('暂无跳转链接');
        }
      }
    },
    /**
     * @description: 获取底部导航
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-22 14:39:36
     * @return {*}
     */
    async getTabbar () {
      const res = await getPart(this.filterPath('type', 'tabbar'), this.templateType);
      if (res) {
        this.tabBar = JSON.parse(res.component)[0];
        localStorage.setItem('tabBar', JSON.stringify(this.tabBar));
      }
      if (this.$route.query.urlname) {
        await this.getHome(this.$route.query.urlname);
      } else {
        if (this.tabBar) {
          await this.getHome(this.tabBar.setStyle.iconList[0].url);
        }
      }
    },
    async getHome (navUrl) {
      console.log(navUrl, 'navUrl');
      this.channelList = [];
      this.iframeUrl = '';
      localStorage.setItem('currentSubjectCode', '');
      const urlname = getParameter(navUrl, 'alias'),
      homeRes = await getPart(this.filterPath('alias', urlname), this.templateType);
      this.homeList = JSON.parse(homeRes.component);
      this.homeTemplateJson = JSON.parse(homeRes.templateJson);
      this.headList = this.homeList.filter(item => item.component === matchingData.headerinformation)[0]; // 头部固定位接口数据
      this.navList = this.filterGrade(localStorage.getItem('gradeCode'), this.homeList); // 选项卡接口数据
      console.log(this.navList, '排查this.navList');
      this.headColor = this.navList.setStyle.optionList[0].bgcolor;
      if (this.navList.setStyle.optionList[0].url.indexOf('.json') !== -1) {
        const url = getParameter(this.navList.setStyle.optionList[0].url, 'alias'),
        channelRes = await getPart(this.filterPath('alias', url), this.templateType);
        if (channelRes) {
          this.channelList = JSON.parse(channelRes.component);
          console.log(this.channelList, 'pooooobinh');
          this.currentSubjectCode = '';
          this.currentSubjectCode = JSON.parse(channelRes.templateJson).subjectCode;
          localStorage.setItem('currentSubjectCode', this.currentSubjectCode);
          let newArrids = [];
          this.channelList.forEach(item => {
            if (item.setStyle.imageList !== undefined) {
              item.setStyle.imageList.map(ite => {
                newArrids.push(ite.id);
              });
            }
          });
          newArrids = newArrids.filter(item => item !== undefined);
          this.ids = newArrids.toString();
        }
      } else {
        this.iframeUrl = JSON.parse(this.navList.setStyle.optionList[0].url).mobileUrl ? (window.location.origin + JSON.parse(this.navList.setStyle.optionList[0].url).mobileUrl) : '';
      }
    },
    /**
     * @description: 筛选年级对应的导航
     * @param {*} gradeCode
     * @param {*} list
     * @Author: ckk
     * @Date: 2022-08-23 10:45:31
     * @return {*}
     */
    filterGrade (gradeCode, list) {
      var result = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].setStyle.optionList) {
          const grade = list[i].setStyle.optionList[0].classList.filter(item1 => item1.gradeCode && (item1.gradeCode === gradeCode));
            if (grade.length > 0) {
              result = list[i];
              break;
            }
        }
      }
      return result;
    },
    /**
     * @description: 返回组件的json路径
     * @param {*} name 需要查的字段
     * @param {*} type 字段值
     * @Author: ckk
     * @Date: 2022-08-23 16:45:25
     * @return {*}
     */
    filterPath (name, type) {
      const fiterPath = this.mainList.filter(item => item[name] === type);
      return fiterPath.length > 0 ? fiterPath[fiterPath.length - 1].jsonPath : '';
    }
  }
};
</script>
<style scoped lang="scss">
.home {
  background: #f6f3f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header{
  flex-shrink: 0;
}
.container {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  margin-bottom:20px;
  iframe{
    width:100%;
    height: 100%;
    margin-top: 10px;
  }
}
</style>
<style lang="scss">
.home{
  .van-tab__text{
    white-space: nowrap;
    overflow: unset;
  }
}
</style>
